from PyQt5.QtSql import QSqlQueryModel, QSqlQuery, QSqlTableModel
from PyQt5.QtWidgets import QAbstractItemView, QMainWindow, QApplication, QMessageBox, QCheckBox, QMenu, QCompleter, \
    QFileDialog, QStyle
from PyQt5 import QtWidgets, QtSql, QtGui, QtCore
from PyQt5.QtWidgets import QStyledItemDelegate, QLineEdit
from PyQt5.QtCore import QDateTime, Qt
import os
import csv
import config_json
import openpyxl
import traceback
import getpath
from openpyxl import load_workbook
import ui_mainw
import json
import subprocess
import bjItems
from FlowLayout import FlowLayout
# import ajlpdf
# import icap
import re
from DlgYanghua import DlgYanghua
from single import SingleApplication
import logging
import datetime
import ejff
import mydb
import myglobal
from PIL import Image as PILImage
from openpyxl.drawing.image import Image
from delegates import FloatEditDelegateQt,NotEditDelegate,DoubleDelegate
import d4460
from cali import Cali
import time
import spec
def timestr():
    db = QDateTime.currentDateTime()
    db_str = db.toString("yyyy_MM_dd_hh_mm_ss")
    return db_str

def myfloat(f):
    try:
        r = float(f)
    except ValueError:
        r = 0
    return r


def inList(one, l):
    for i in range(len(l)):
        # logging.info(one, l[i])
        if one in l[i]:
            return i
    return -1


def addUsed(l, one):
    new = one.split(" ")
    for i in range(len(l)):
        l1 = l[i].split(" ")
        if new[0] == l1[0]:  # in list update
            l[i] = one
            return
    l.append(one)


def is_int(a_string):
    try:
        int(a_string)
        return True
    except ValueError:
        return False


def is_float(a_string):
    try:
        float(a_string)
        return True
    except ValueError:
        return False
class MainW(QMainWindow):
    ui = ui_mainw.Ui_MainWindow()

    def contextMenuEvent(self, event):
        menu = QMenu(self)
        allAction = menu.addAction("全部")
        noneAction = menu.addAction("全部不选")
        usedAction = menu.addAction("用过的")
        quitAction = menu.addAction("第一个")
        validAction = menu.addAction("去除无效")
        multiAction = menu.addAction("*0.4")
        multiAction2 = menu.addAction("*0.8")
        action = menu.exec_(self.mapToGlobal(event.pos()))
        if action == quitAction:
            self.firstChannel()
        elif action == usedAction:
            self.usedChannel()
        elif action == noneAction:
            self.noneChannel()
        elif action == allAction:
            self.allChannel()
        elif action == validAction:
            self.validChannel()
        elif action == multiAction:
            self.massMulti(0.4)
        elif action == multiAction2:
            self.massMulti(0.8)
    def massMulti(self,xs):
        selections = self.ui.tableView_report.selectionModel()
        list1 = selections.selectedIndexes()
        for i in range(len(list1)):
            current = list1[i]
            if current.column() == 0:
                row = current.row()
                record = self.model2.record(row)
                mass=myfloat(record.value(record.indexOf("mass")))
                mass=mass*xs
                m="%0.4f" % mass #保留小数点后4位
                m=float(m)
                self.model2.setData(self.model2.index(row,3 ), m) #mass
                vol=myfloat(record.value(record.indexOf("volume")))
                self.model2.setData(self.model2.index(row,4 ), vol*xs*10) #mass
                logging.info([row,mass,m])
                self.model2.submitAll()
    def closeEvent(self, event):
        myglobal.db.saveCurrent()
        config_json.write_setting()
        event.accept()

    # def set_database(self):
    #     if config_json.setting['database'] is None:
    #         return False
    #     self.connection = QtSql.QSqlDatabase.addDatabase(
    #         "QSQLITE")  # ', connID);
    #     # self.connection.setDatabaseName(":memory:")
    #     self.connection.setDatabaseName(os.path.join(getpath.getpath(), "data.sqlite"))
    #     if not self.connection.open():
    #         logging.debug("open failed")
    #         return False
    #     return True

    def selectChannel(self, pos):
        logging.info("selectChannel")
        logging.info(pos)
        it = self.ui.tableView_report.columnAt(pos.x())  # 根据鼠标坐标获取列号
        logging.info(it)
        # self.title = ["id", "time", "sampleid", "mass", "volume"]
        title = self.model2.headerData(it, Qt.Horizontal)
        if it > self.eleColumns - 1:
            self.columnVisible(it, False)

    def yanghua(self, pos):
        logging.info("yanghua")
        logging.info(pos)
        it = self.ui.tableView_report.columnAt(pos.x())  # 根据鼠标坐标获取列号
        logging.info(it)
        # self.title = ["id", "time", "sampleid", "mass", "volume"]
        title = self.model2.headerData(it, Qt.Horizontal)
        if it > self.eleColumns - 1:
            one = self.fields[it]
            logging.info(one)
            d = DlgYanghua()
            d.ui.label_element.setText(one["title"])
            tit = one["title"].split(' ')[0]
            d.ui.edit_yanghua.setText(tit)
            d.ui.edit_xishu.setText(str(one.get("xishu")))
            r = d.exec_()
            if r == 1:
                self.changeYanghua(
                    it, d.ui.edit_yanghua.text(), d.ui.edit_xishu.text())
            else:
                pass

    def changeYanghua(self, i, yanghua, xishu):
        logging.info(str(i)+","+yanghua+","+str(xishu))
        self.fields[i]["xishu"] = float(xishu)
        titles = self.fields[i]["title"].split(" ")
        newtitle=" ".join([yanghua, titles[1]])
        self.fields[i]["title"]= newtitle
        self.chks[i].setText(newtitle)
        self.model.setHeaderData(i, Qt.Horizontal, self.fields[i]["title"])
        self.model2.setHeaderData(i, Qt.Horizontal, self.fields[i]["title"])

    def showCloumnMenu(self, pos):
        logging.info("showCloumnMenu")
        logging.info(pos)
        it = self.ui.tableView_report.columnAt(pos.x())  # 根据鼠标坐标获取列号
        logging.info(it)
        # self.title = ["id", "time", "sampleid", "mass", "volume"]
        title = self.model2.headerData(it, Qt.Horizontal)
        if it > self.eleColumns - 1:
            menu = QMenu()
            # self.yanghua)
            menu.addAction("氧化物", lambda val=pos: self.yanghua(val))
            # self.yanghua)
            menu.addAction("移除", lambda val=pos: self.selectChannel(val))
            pos = self.ui.tableView_report.horizontalHeader().viewport().mapToGlobal(pos)
            return menu.exec_(pos)

    def __init__(self, parent=None):
        super().__init__(parent)
        n=datetime.datetime.now().year % 2000
        n0=n-1
        n=str(n)
        n0=str(n0)
        self.sample_name_pattern="(%s|%s)[A-Z][A-Z][0-9]*-[1-9]" % (n,n0)
        self.completer = None
        self.eleColumns = 0
        self.ct = 0
        self.connection = None
        self.ui.setupUi(self)
        config_json.read_setting()
        self.ejff=ejff.ejff()
        if config_json.setting["sblx"] not in config_json.setting["sblx_list"]:
            config_json.setting["sblx"]=config_json.setting["sblx_list"][0]
        if config_json.setting["style"]==1:
            import qss_rc
            if config_json.setting["dark"]:
                self.qingyun_style(True)
            else:
                self.qingyun_style(False)
        # self.ui.cmb_ff2.setVisible(False)
        # self.ui.cmb_js2.setVisible(False)
        # self.ui.label_js2.setVisible(False)
        # self.ui.label_ff2.setVisible(False)
        self.setWindowTitle("数据上报——" + config_json.setting["sblx"])
        myglobal.db=mydb.MyDb()
        myglobal.methodid=myglobal.db.methodid()
        # self.set_database()
        self.fields = []
        self.chks = []
        self.ncol = 0
        self.m_cBoxDelegate = DoubleDelegate()
        self.notedit = NotEditDelegate()
        self.edit_delegate=FloatEditDelegateQt()
        self.ids = []
        self.idStr = "()"
        self.model = QSqlTableModel()
        self.model2 = QSqlTableModel()
        # self.model.setTable("result")
        # self.ui.tableView.setModel(self.model)

        self.ui.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.ui.tableView_report.horizontalHeader(
        ).setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.tableView_report.horizontalHeader(
        ).customContextMenuRequested.connect(self.showCloumnMenu)

        self.ui.btnSelect.clicked.connect(self.select)
        self.ui.btnUnselect.clicked.connect(self.unselect)
        self.ui.btnClear.clicked.connect(self.clear)
        self.ui.btnLims.clicked.connect(self.lims)
        self.ui.pushButton_import.clicked.connect(self.import_click)
        # self.ui.pushButton_clearDB.clicked.connect(self.clearDB_click)
        self.ui.pushButton_clearDB.setVisible(False)  # not use
        self.ui.actionsetting.triggered.connect(self.setting)
        self.ui.actionffbh.triggered.connect(self.set_ffbh)
        self.ui.action_exit.triggered.connect(self.exit_app)
        self.ui.actionsave_as.triggered.connect(self.save_as)
        self.ui.actionsyy.triggered.connect(self.set_syy)
        self.h = FlowLayout(self.ui.groupBox)
        # self.model2.setTable("result")

        # self.ui.tableView_report.setModel(self.model2)
        self.ui.tableView_report.setSelectionBehavior(
            QAbstractItemView.SelectRows)

        self.refresh_ffbh()
        self.refresh_syy()
        self.ui.lineEdit_yqbh.setText(config_json.setting["yqbh"])
        # self.ui.lineEdit_nb.setText(config_json.setting["nb"])
        # self.ui.lineEdit_nd.setText(str(config_json.setting["nd"]))
        # self.ui.lineEdit_bc.setText(str(config_json.setting["bc"]))
        # self.ui.lineEdit_tpbh.setText(config_json.setting["tpbh"])
        self.ui.cmb_syy.currentIndexChanged[int].connect(self.syy_change)
        self.ui.cmb_ysry.currentIndexChanged[int].connect(self.ysry_change)
        self.ui.cmb_ffbh.currentIndexChanged[int].connect(self.ffbh_change)
        self.ui.cmb_syyqm.currentIndexChanged[int].connect(self.syyqm_change)
        self.ui.pushButton_last.clicked.connect(self.import_last)
        self.ui.action_version.triggered.connect(self.version)
        self.ui.action_upgrade.triggered.connect(self.upgrade)
        self.ui.action_sync.setVisible(False)
        self.ui.action.setVisible(False)
        self.ui.action_sync.triggered.connect(self.sync)
        self.ui.btnSelectAll.clicked.connect(self.selectAll)
        self.ui.actionQt.triggered.connect(QtWidgets.qApp.aboutQt)
        self.ui.pushButton_calc.clicked.connect(self.calc)

        # self.ui.pushButton.clicked.connect(self.import_std_result)
        # self.ui.pushButton_std.clicked.connect(self.import_std)
        # self.q=QtSql.QSqlQuery()
        # logging.info(dir(self.windowHandle()))#.screen())
        if config_json.setting["style"]==1:
            self.action_style_dark = QtWidgets.QAction(self)
            self.action_style_dark.setText("暗色")
            self.action_style_dark.triggered.connect(self.style_dark)
            self.ui.menu.addAction(self.action_style_dark)
            self.action_style_light = QtWidgets.QAction(self)
            self.action_style_light.setText("亮色")
            self.action_style_light.triggered.connect(self.style_light)
            self.ui.menu.addAction(self.action_style_light)
        # self.action_style_0 = QtWidgets.QAction(self)
        # self.action_style_0.setText("styles")
        # self.action_style_0.triggered.connect(self.style_0)
        # self.action_styles.addAction(self.action_style_0)
        logging.info(["mainw load finish",time.perf_counter()])
    def qingyun_style(self,dark):
        a=QtWidgets.qApp
        # f=open("qss/lightblue.css", "r") 
        # f=open("qss/blacksoft.css", "r") 
        if dark:
            fname="blacksoft.css"
        else:
            fname="flatgray.css"
        f=open(os.path.join(getpath.getpath(),"qss",fname),"r")#"flatgray.css"), "r") 
        _style = f.read()
        # print(_style)
        paletteColor=_style[20:20+7]
        # print(paletteColor)
        a.setPalette(QtGui.QPalette(QtGui.QColor(paletteColor)));
        a.setStyleSheet(_style);    
    def style_dark(self):
        self.qingyun_style(True)
        config_json.setting["dark"]=1
    def style_light(self):
        config_json.setting["dark"]=0
        self.qingyun_style(False)
        pass
    def calc(self):
        if myglobal.cali==None:
            myglobal.cali = Cali()
            myglobal.cali.show()
        else:
            pass
            # print(dir(self.cali))
            # self.cali.activeWindow()
        # if r == 1:
        #     # self.refresh_ffbh()
        #     pass
        # else:
        #     pass
    def cali_close(self):
        self.cali=None
    def getff2(self,ff):
        logging.info(ff)
        r=[]
        for one in self.ejff:
            # logging.info(ff,one[0])
            if len(one)<4:
                continue
            if ff==one[0]:
                r.append((one[2],one[3]))
            else:
                pass
        logging.info(r)
        return r
    def selectAll(self):
        for row in range(self.model.rowCount()):
            record = self.model.record(row)
            self.calc_one(record)
        self.model2.select()
    def calc_one(self,record):
        sample = {"items": [], "conc": []}
        sample["sampleid"]=record.value(record.indexOf("sampleid"))
        sample["oldid"]=record.value(record.indexOf("id"))
        for i in range(len(self.fields)):
            f = self.fields[i]
            ele=f.get("ele")
            if ele==None:
                pass
            else:
                sample["items"].append(("ele",""))
                conc0 = myfloat(record.value(record.indexOf(ele+"_")))
                conc=self.calc_ele(conc0,ele)
                sample["conc"].append(conc)
                print(ele,conc)
        self.iTable(sample,"Result",1)#calced=1

    def calc_ele(self,conc0,ele):
        xishu=myglobal.db.getXishuCurrent(myglobal.methodid,ele)
        if xishu==None:
            return conc0
        else:
            [x2,x1,x0,r,cid,must00,ci]=xishu
            return x2*conc0*conc0+x1*conc0+x0
    def sync(self):
        src_path = r"""\\10.0.114.230\化学分析室\仪器采集\reports\report_icp"""
        file_name = os.path.join(src_path,"_internal", "setting.json")
        logging.info('Reading %s...' % file_name)
        try:
            file=open(file_name, encoding="utf-8")
            new_setting = json.load(file)
            file.close()
            # ffbh_cs
            (left, right) = bjItems.bjitems(
                config_json.setting["ffbh"], new_setting["ffbh"])
            # logging.info(left, right)
            for one in right:
                config_json.setting["ffbh"].append(one)
            for one in left:
                new_setting["ffbh"].append(one)
            # syy
            (left, right) = bjItems.bjitems(
                config_json.setting["syy"], new_setting["syy"])
            # logging.info(left, right)
            for one in right:
                config_json.setting["syy"].append(one)
            for one in left:
                new_setting["syy"].append(one)
            # output
            set_file=open(file_name, 'w', encoding="utf-8")
            json.dump(new_setting, set_file, indent=4)
            set_file.close()
        except FileNotFoundError as e:
            pass
        except json.decoder.JSONDecodeError:
            pass

    def version(self):
        QMessageBox.about(self, '版本号', config_json.setting["version"])

    def upgrade(self):
        src_path = r"""\\10.0.114.230\化学分析室\仪器采集\reports\report_icp"""
        file_name = os.path.join(src_path,"_internal", "setting.json")
        logging.info('Reading %s...' % file_name)
        file=open(file_name, encoding="utf-8")
        new_setting = json.load(file)
        file.close()
        new_version = int(new_setting["version"])
        version = int(config_json.setting["version"])
        if new_version > version:
            # logging.info("has new_version", new_version)
            r = QMessageBox.question(
                self, '升级', '是否升级', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            if r == QMessageBox.Yes:
                logging.info("yes")
                self.close()
                args = ["xcopy.exe", "/Y", src_path, getpath.getpath()]
                subprocess.Popen(args, creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, close_fds=True)
            else:
                logging.info("no")
        else:

            logging.info("not new_version "+str(new_version))
        pass

    def import_last(self):
        try:
            self.import_file(config_json.setting["database"])
        except:
            traceback.print_exc()

    def ysry_change(self, at):
        config_json.setting["current"]["ysry"] = at

    def syyqm_change(self, at):
        config_json.setting["current"]["syyqm"] = at

    def ffbh_change(self, at):
        config_json.setting["current"]["ffbh"] = at
        ff=self.ui.cmb_ffbh.currentText()
        r=self.getff2(ff)
        self.ui.cmb_ff2.clear()
        self.ui.cmb_js2.clear()
        self.ui.cmb_ff2.addItem("")
        self.ui.cmb_js2.addItem("")
        for one in r:
            self.ui.cmb_ff2.addItem(one[0])
            self.ui.cmb_js2.addItem(one[1])
        self.ui.cmb_ff2.setCurrentIndex(self.ui.cmb_ff2.count()-1)
        self.ui.cmb_js2.setCurrentIndex(self.ui.cmb_js2.count()-1)

    def syy_change(self, at):
        self.ui.cmb_syyqm.setCurrentIndex(at)
        config_json.setting["current"]["syy"] = at

    def clearLayout(self, layout):
        while True:
            child = layout.takeAt(0)
            # logging.info(child)
            if child is None:
                break
            else:
                # logging.info(dir(child))
                child.widget().deleteLater()

    def usedChannel(self):
        for i in range(len(self.fields)):
            f = self.fields[i]
            if f.get("ele") is None:
                pass
            else:
                if f["title"] in config_json.setting["visible"]:
                    self.columnVisible(i, True)
                else:
                    self.columnVisible(i, False)

    def allChannel(self):
        for i in range(len(self.fields)):
            if self.fields[i].get("ele") is None:
                pass
            else:
                self.columnVisible(i, True)
    def noneChannel(self):
        for i in range(len(self.fields)):
            if self.fields[i].get("ele") is None:
                pass
            else:
                self.columnVisible(i, False)
    def validChannel(self):
        for row in range(self.model.rowCount()):
            record = self.model.record(row)
            for i in range(len(self.fields)):
                one = self.fields[i]
                if one.get("ele") is None:
                    pass
                else:
                    if record.value(record.indexOf(one["name"])) == "-":
                        self.columnVisible(i, False)
            break

    def sortFields(self):
        r = []
        groups = {}
        for i in range(len(self.fields)):
            f = self.fields[i]
            if f.get("ele") is None:
                r.append(f)
                pass
            else:
                element = f["ele"]
                if groups.get(element) is None:
                    groups[element] = []
                groups[element].append(f)
        for one in groups.keys():
            for i in range(len(groups[one])):  # wave in groups[one]:
                r.append(groups[one][i])
        self.fields = r

    def firstChannel(self):
        try:
            groups = {}
            for i in range(len(self.fields)):
                f = self.fields[i]
                if f.get("ele") is None:
                    pass
                else:
                    element = f["ele"]
                    wave = f["wave"]
                    if groups.get(element) is None:
                        groups[element] = []
                    groups[element].append(f)
            for one in groups.keys():
                # logging.info(groups[one])
                for i in range(len(groups[one])):  # wave in groups[one]:
                    if i == 0:
                        groups[one][i]["visible"] = True
                    else:
                        groups[one][i]["visible"] = False
            for i in range(len(self.fields)):
                if self.fields[i].get("ele") is None:
                    pass
                else:
                    self.columnVisible(i, self.fields[i]["visible"])

        except ValueError as e:
            pass

    def genchks(self):
        if len(self.chks) < len(self.fields):
            # logging.info(list(range(len(self.chks), len(self.fields))))
            for i in range(len(self.chks), len(self.fields)):
                c = QCheckBox("")
                self.h.addWidget(c)
                c.pressed.connect(
                    lambda val=i: self.field_click(val)
                )
                self.chks.append(c)

    def resetItems(self):
        self.genchks()
        logging.info(len(self.chks))
        for i in range(len(self.fields)):
            if self.fields[i].get("ele") is None:
                self.chks[i].setVisible(False)
            else:
                self.chks[i].setChecked(self.fields[i]["visible"])
                self.chks[i].setText(self.fields[i]["title"])
                self.chks[i].setVisible(True)
        for i in range(len(self.fields), len(self.chks)):
            self.chks[i].setVisible(False)
        self.init_grid()

    def columnVisible(self, i, visible):
        self.fields[i]["visible"] = visible
        if visible:
            self.chks[i].setChecked(True)
            self.ui.tableView_report.showColumn(i)
            self.ui.tableView.showColumn(i)
        else:
            self.chks[i].setChecked(False)
            self.ui.tableView_report.hideColumn(i)
            self.ui.tableView.hideColumn(i)

    def clearResult(self):
        myglobal.db.dropTable("result")
        self.clear()
    def import_click(self):
        FileDialog = QFileDialog(self)
        if config_json.setting["database"]==None:
            folder=os.path.join(os.path.expanduser('~'), "Desktop")
        else:
            folder = os.path.split(config_json.setting["database"])[0]
        # if config_json.setting["sblx"] == "ajl_csv":
        #     fil = "csv Files (*.csv);;All Files (*)"
        # el
        if config_json.setting["sblx"] in ["spec","4460"]:
            fil = "xlsx Files (*.xlsx);;All Files (*)"
        # elif config_json.setting["sblx"] == "ajl_pdf":
        #     fil = "pdf Files (*.pdf);;All Files (*)"
        # elif config_json.setting["sblx"] == "icap":
        #     fil = "Html Files (*.html);;All Files (*)"
        else:
            fil = "All Files (*)"
        FileDirectory = FileDialog.getOpenFileName(
            self, 'select import file', folder, fil)  # 选择目录，返回选中的路径
        # logging.info(FileDirectory)
        fname = FileDirectory[0]
        if fname == "":
            pass
        else:
            try:
                self.import_file(fname)
            except:
                traceback.print_exc()

    def import_file(self, fname):
        myglobal.db.dropTable("Result")
        # return
        config_json.setting["database"] = fname
        # if config_json.setting["sblx"] in ["ajl_csv"]:
        #     self.import_ajl_csv(fname)
        # elif config_json.setting["sblx"] == "ajl_pdf":
        #     self.import_ajl_pdf(fname)
        # elif config_json.setting["sblx"] == "icap":
        #     self.import_icap(fname)
        if config_json.setting["sblx"] in ["spec"]:
            self.import_spec(fname)
        elif config_json.setting["sblx"] in ["4460"]:
            self.import_4460(fname)
        elif config_json.setting["sblx"] in ["002"]:
            self.import_002(fname)
        else:
            self.import_file_bytitle(fname)
        self.resetItems()

    def inSamples(self, samples, one):
        at = 0
        for s in samples:
            if s["sampleid"] == one:
                return at
            at += 1
        return -1

    def inItems(self, items, one):
        for s in items:
            if s[0] == one[0] and s[1] == one[1]:
                return True
        return False

    def newSample0(self, samples, sampleid, ele, wave, conc, mass, volume):
        # sampleid can not be duplicate,so must with _1,_2
        at = self.inSamples(samples, sampleid)
        if at != -1:
            if self.inItems(samples[at]["items"], (ele, wave)):
                pass
            else:
                samples[at]["conc"].append(conc)
                samples[at]["items"].append((ele, wave))
            return False
        else:
            samples.append({"mass": mass, "volume": volume, "sampleid": sampleid, "conc": [
                conc], "items": [(ele, wave)]})
            return True

    def newSample(self, samples, sampleid, ele, wave, conc, mass, volume):
        # can not same sampleid followed
        if len(samples) >= 1:
            sample = samples[-1]
            if sampleid == sample["sampleid"]:  # same sampleid with last
                at2 = self.inItems(sample["items"], (ele, wave))
                if at2:  # same element wave donot capture
                    pass
                else:
                    sample["conc"].append(conc)
                    sample["items"].append((ele, wave))
                return False
            else:
                samples.append({"mass": mass, "volume": volume, "sampleid": sampleid, "conc": [
                    conc], "items": [(ele, wave)]})
                return True
        else:  # []
            samples.append({"mass": mass, "volume": volume, "sampleid": sampleid, "conc": [
                conc], "items": [(ele, wave)]})
            return True

    def elementWave(self, s):
        if s==None:
            return("","")
        wave = re.search(r"\d+(\.\d+)?", s)
        if wave!=None:
            wave=wave.group()
            element = s.split(" ")[0]
        else:
            wave=""
            element=s
        return (element, wave)
# 标签  开始时间    取样量 稀释因子    Mn 257.610 (Aqueous-Radial-iFR) []  Cr 267.716 (Aqueous-Radial-iFR) [%] Cr 284.325 (Aqueous-Radial-iFR) [%] Mn 293.930 (Aqueous-Radial-iFR) []  Cu 324.754 (Aqueous-Radial-iFR) [%] Cu 327.396 (Aqueous-Radial-iFR) [%] Y 360.073 (Aqueous-Radial-iFR) [%]
    # def import_icap(self, fname):
    #     (data, mass) = icap.getDataAndMass(fname)
    #     create_table = False
    #     samples = []
    #     at = 1
    #     while True:
    #         sample = {"items": [], "conc": []}
    #         try:
    #             sample["items"] = data[0][4:]
    #             sampleid = data[at][0]
    #             sample["sampleid"] = data[at][0].replace('\n', '')
    #             sample["mass"] = str(myfloat(data[at][2])/10)
    #             sample["volume"] =str(myfloat(data[at][3])*100)
    #             sample["xishi"] = ""
    #             logging.info(sampleid)
    #             sample["conc"] = []
    #             for one in data[at][4:]:
    #                 sample["conc"].append(one)  # remove %
    #             for i in range(len(sample["items"])):
    #                 fs=sample["items"][i].split(" ")
    #                 ele=fs[0]
    #                 wave=fs[1]
    #                 sample["items"][i] = (ele, wave)
    #         except IndexError:
    #             break
    #         if not create_table:
    #             self.cTable(sample,"Result")
    #             create_table = True
    #         self.iTable(sample,"Result")
    #         if sampleid == "":
    #             break
    #         samples.append(sample)
    #         at += 1
    #     logging.info(samples)
    #     logging.info(len(samples))
    # 溶液标签    Cu (324.754nm)  Cu (327.395nm)  Mg (279.553nm)  Mg (280.270nm)  Mn (257.610nm)  Mn (293.305nm)  P (178.222nm)   P (178.703nm)   Si (184.685nm)  Si (185.005nm)  V (326.769nm)   V (327.612nm)   Zr (339.198nm)  Zr (343.823nm)  mass    volume
    # BLK -0.000005 (%)   -0.000009 (%)   0.000000 (%)    -0.000001 (%)   0.000001 (%)    -0.000010 (%)   -0.000004 (%)   -0.000195 (%)   0.000026 (%)    -0.000016 (%)   0.000019 (%)    -0.000008 (%)   -0.000004 (%)   -0.000002 (%)   1   1
    # def import_ajl_pdf(self, fname):
    #     # data=ajlpdf.getData(fname)
    #     (data, mass) = ajlpdf.getDataAndMass(fname)
    #     # self.page_curve = i
    #     create_table = False
    #     samples = []
    #     at = 1
    #     while True:
    #         sample = {"items": [], "conc": []}
    #         try:
    #             sample["items"] = data[0][1:]
    #             sampleid = data[at][0]
    #             sample["sampleid"] = data[at][0].replace('\n', '')
    #             sample["mass"] = mass[at][0]
    #             sample["volume"] = mass[at][1]
    #             logging.info(sampleid)
    #             sample["conc"] = []
    #             for one in data[at][1:]:
    #                 sample["conc"].append(one.split(" ")[0])  # remove %
    #             for i in range(len(sample["items"])):
    #                 (ele, wave) = self.elementWave(sample["items"][i])
    #                 sample["items"][i] = (ele, wave)
    #         except IndexError:
    #             break
    #         if not create_table:
    #             self.cTable(sample)
    #             create_table = True
    #         self.iTable(sample)
    #         if sampleid == "":
    #             break
    #         samples.append(sample)
    #         at += 1
    #     logging.info(samples)
    #     logging.info(len(samples))

    # def import_ajl_csv(self, fname):
    #     # 标签  类型  元素  元素标签    浓度  单位  强度  浓度 SD   重量  体积  稀释系数
    #     # BLK 样品  Ce 399.924  Ce  0.000025    %   29.7774 0.000028    1   1   1
    #     file=open(
    #         fname, encoding=config_json.setting[config_json.setting["sblx"]]["encoding"])
    #     csv_reader = csv.reader(file)
    #     row_index = 0
    #     samples = []
    #     create_table = False
    #     for row in csv_reader:
    #         logging.info(row)
    #         if row_index >= 6:
    #             sampleid = row[0]
    #             (ele, wave) = row[2].split(" ")
    #             conc = row[7]
    #             mass = row[8]
    #             volume = myfloat(row[9])*100
    #             n = self.newSample(samples, sampleid,
    #                                ele, wave, conc, mass, volume)
    #             if n:
    #                 if (len(samples) - 2) >= 0:  # save last
    #                     sample = samples[len(samples) - 2]
    #                     if not create_table:
    #                         self.cTable(sample)
    #                         create_table = True
    #                     self.iTable(sample)
    #             else:
    #                 pass
    #         else:
    #             pass
    #         row_index += 1
    #     file.close()
    #     #save last
    #     if not create_table:
    #         self.cTable(sample)
    #     self.iTable(sample)
 
    def import_002(self, fname):
        # 溶液标签    "P (213.618nm)"    "P (214.914nm)"    "Pb (217.000nm)"    "Pb (220.353nm)"    "Ta (226.142nm)"    "Ta (226.230nm)"    "Ti (334.188nm)"    "Ti (334.941nm)"
        # BLK 0.000026 (%)    -0.000214 (%)   0.000659 (%)    0.000601 (%)    -0.000040 (%)   -0.000028 (%)   -0.000051 (%)   -0.000001 (%)
        logging.info("import_002=======================")
        file=open(
            fname, encoding=config_json.setting[config_json.setting["sblx"]]["encoding"])
        csv_reader = csv.reader(file)
        data = []
        for row in csv_reader:
            data.append(row)
        file.close()
        create_table = False
        samples = []
        at = 1
        while True:
            sample = {"items": [], "conc": []}
            try:
                sample["mass"] = "0"
                sample["volume"] = "0"
                sample["items"] = data[0][1:]
                sampleid = data[at][0]
                sample["sampleid"] = data[at][0]
                sample["conc"] = []
                for one in data[at][1:]:
                    sample["conc"].append(one.split(" ")[0])  # remove %
                for i in range(len(sample["items"])):
                    (ele, wave) = self.elementWave(sample["items"][i])
                    sample["items"][i] = (ele, wave)
                logging.info(sampleid)
            except IndexError:
                break
            if not create_table:
                self.cTable(sample)
                create_table = True
            self.iTable(sample)
            if sampleid == "":
                break
            samples.append(sample)
            at += 1
        logging.info(samples)
        logging.info(len(samples))
    def import_4460(self, fname):
        # 溶液标签    "P (213.618nm)"    "P (214.914nm)"    "Pb (217.000nm)"    "Pb (220.353nm)"    "Ta (226.142nm)"    "Ta (226.230nm)"    "Ti (334.188nm)"    "Ti (334.941nm)"
        # BLK 0.000026 (%)    -0.000214 (%)   0.000659 (%)    0.000601 (%)    -0.000040 (%)   -0.000028 (%)   -0.000051 (%)   -0.000001 (%)
        logging.info("import_4460=======================")
        # file=open(
        #     fname, encoding=config_json.setting[config_json.setting["sblx"]]["encoding"])
        # csv_reader = csv.reader(file)
        # data = []
        # for row in csv_reader:
        #     data.append(row)
        # file.close()
        data=d4460.getdata(fname)
        create_table = False
        samples = []
        at = 1
        while True:
            sample = {"items": [], "conc": []}
            try:
                sample["mass"] = "0"
                sample["volume"] = "0"
                sample["items"] = data[0][1:]
                sampleid = data[at][0]
                sample["sampleid"] = data[at][0]
                sample["conc"] = []
                for one in data[at][1:]:
                    sample["conc"].append(one)  # remove %
                for i in range(len(sample["items"])):
                    (ele, wave) = self.elementWave(sample["items"][i])
                    sample["items"][i] = (ele, wave)
                logging.info(sampleid)
            except IndexError:
                break
            if not create_table:
                self.cTable(sample)
                create_table = True
            self.iTable(sample)
            if sampleid == "":
                break
            samples.append(sample)
            at += 1
        logging.info(samples)
        logging.info(len(samples))
    def import_spec(self, fname):
        xlBook = load_workbook(filename=fname)
        table = xlBook.worksheets[0]
        logging.info(dir(table))
        create_table = False
        data = []
        for row in table.values:
            r = []
            for one in row:
                if one is not None:
                    r.append(one)
                else:
                    r.append(None)
            data.append(r)
        samples = []
        at = 0
        while True:
            sample = {"items": [], "conc": []}
            try:
                sampleid = data[at + 1][0]
                sample["sampleid"] = sampleid

                logging.info(sampleid)
            except IndexError:
                break
            col = 1
            while True:
                try:
                    # logging.info(at+2,col)
                    item = data[at + 2][col]
                    conc = data[at + 3][col]
                    # should replace blank to other char
                    sample["items"].append((item, ""))  # .append(item + "_")
                    sample["conc"].append(conc)
                    sample["mass"] = ""
                    sample["volume"] = ""
                except IndexError:
                    break
                if (item == ""):
                    break
                col += 1
            if not create_table:
                self.cTable(sample)
                create_table = True
            self.iTable(sample)
            if sampleid == "":
                break
            samples.append(sample)
            at += 7
        logging.info(samples)
        logging.info(len(samples))

    def cTable(self, sample,tablename="Result"):
        self.fields = [{"ele": None, "name": "id", "title": "id", "visible": False
                        }, {"ele": None, "name": "sampleid", "title": "样品编号", "visible": True
                            }, {"ele": None, "name": "calced", "title": "计算", "visible": False
                                }, {"ele": None, "name": "oldid", "title": "oldid", "visible": False
                                }, {"ele": None, "name": "beizhu", "title": "备注", "visible": True
                                }]
        self.eleColumns = len(self.fields)
        for item in sample["items"]:
            logging.info(item)
            title = item[0]+" "+item[1]
            # to valid column name
            name = item[0]+"_"+item[1].replace(".", "Q")
            self.fields.append(
                {"ele": item[0], "wave": item[1], "name": name, "title": title, "visible": True})
        # if config_json.setting["sblx"] in ["ajl_csv","icap"]:
        #     self.sortFields()
        cmd = """CREATE TABLE """+tablename+""" (
id       INTEGER  PRIMARY KEY AUTOINCREMENT
                    NOT NULL,
sampleid varchr,
calced bool,
oldid integer,
beizhu  varchr,
%s)""" % self.genSqlArrDeclare_new()
        logging.info(cmd)
        myglobal.db.sql_cmd(cmd)
        self.sqlArrName = self.gensqlArrName()

    def iTable(self, sample,tablename="Result",calced=0):
        logging.info(sample)
        q = QSqlQuery()
        xishi=sample.get("xishi","")
        oldid=sample.get("oldid",-1)
        cmd = """insert into """+tablename+""" (
sampleid,calced,oldid,%s) values(%s,%s,%d,%s)""" % (
            self.sqlArrName, "'" +
            sample["sampleid"] + "'",calced,oldid, self.genSqlArr(sample["conc"]))
        logging.info(cmd)
        myglobal.db.sql_cmd(cmd)

    def genSqlArrDeclare_new(self):
        r = []
        for one in self.fields:
            if one.get("ele") is None:
                pass
            else:
                r.append(one["name"] + " varchr")
        return ",".join(r)

    def gensqlArrName(self):
        r = []
        for one in self.fields:
            if one.get("ele") is None:
                pass
            else:
                r.append("'" + one["name"] + "'")
        return ",".join(r)

    def genSqlArr(self, arr):
        r = []
        for one in arr:
            r.append("'" + str(one) + "'")
        return ",".join(r)

    def refresh_ffbh(self):
        ff = config_json.setting["ffbh"]
        self.ui.cmb_ffbh.clear()
        self.ui.cmb_ffbh.addItems(ff)
        self.ui.cmb_ffbh.setCurrentIndex(
            config_json.setting["current"]["ffbh"])
        self.ffbh_change(config_json.setting["current"]["ffbh"])
        self.ui.cmb_ffbh.setEditable(True)
        self.completer = QCompleter(ff, self)
        self.completer.setFilterMode(Qt.MatchContains)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.ui.cmb_ffbh.setCompleter(self.completer)

    def refresh_syy(self):
        ff = config_json.setting["syy"]
        self.ui.cmb_syy.clear()
        self.ui.cmb_syyqm.clear()
        self.ui.cmb_ysry.clear()
        for i in ff:
            self.ui.cmb_syy.addItem(i)
            self.ui.cmb_syyqm.addItem(i)
            self.ui.cmb_ysry.addItem(i)
        self.ui.cmb_syy.setCurrentIndex(config_json.setting["current"]["syy"])
        self.ui.cmb_ysry.setCurrentIndex(
            config_json.setting["current"]["ysry"])
        self.ui.cmb_syyqm.setCurrentIndex(
            config_json.setting["current"]["syyqm"])

    def field_click(self, i):
        logging.info(self.sender())
        logging.info(i)
        logging.info(self.fields[i]["visible"])

        self.fields[i]["visible"] = not self.fields[i]["visible"]
        if self.fields[i]["visible"]:
            # self.chks[i].setChecked(True)
            self.ui.tableView_report.showColumn(i)
            self.ui.tableView.showColumn(i)
        else:
            # self.chks[i].setChecked(False)
            self.ui.tableView_report.hideColumn(i)
            self.ui.tableView.hideColumn(i)

    def init_grid(self):
        self.init_grid1()
        self.init_grid2()

    def init_grid1(self):
        self.model.setTable("result")  # setQuery(cmd)
        self.ui.tableView.setModel(self.model)
        # self.ui.tableView.hideColumn(1)
        self.model.setFilter("calced=0")
        self.model.select()
        for i in range(len(self.fields)):  # hideColumn
            if self.fields[i]["visible"]:
                pass
            else:
                self.ui.tableView.hideColumn(i)
            self.model.setHeaderData(i, Qt.Horizontal, self.fields[i]["title"])
        self.ui.tableView.setColumnWidth(1,120)
        for i in range(len(self.fields)):
            self.ui.tableView.setItemDelegateForColumn(
                i, self.notedit)
        # for i in range(self.eleColumns, len(self.fields)):
        #     self.ui.tableView.setItemDelegateForColumn(
        #         i, self.m_cBoxDelegate)

    def init_grid2(self):
        self.model2.setTable("result")  # setQuery(cmd)
        self.model2.setFilter("calced=1")
        # self.model2.setFilter(" id in  " + self.idStr)
        self.ui.tableView_report.setModel(self.model2)
        # self.ui.tableView.hideColumn(1)
        self.model2.select()
        self.ui.tableView_report.setColumnWidth(1,120)
        for i in range(len(self.fields)):  # hideColumn
            if self.fields[i]["visible"]:
                pass
            else:
                self.ui.tableView_report.hideColumn(i)
            self.model2.setHeaderData(
                i, Qt.Horizontal, self.fields[i]["title"])
        for i in range(2):
            self.ui.tableView_report.setItemDelegateForColumn(
                i, self.notedit)
        # for i in range(3,self.eleColumns):for mass valume
        #     self.ui.tableView_report.setItemDelegateForColumn(
        #         i, self.edit_delegate)
        for i in range(self.eleColumns, len(self.fields)):
            # logging.info(i, 'setIemtDelegate')
            self.ui.tableView_report.setItemDelegateForColumn(
                i, self.m_cBoxDelegate)

    def exit_app(self):
        pass
        # config_json.write_setting()
        self.close()

    def set_ffbh(self):
        from dlgffbh2 import Dlgffbh
        d = Dlgffbh()
        r = d.exec_()
        if r == 1:
            self.refresh_ffbh()
        else:
            pass

    def set_syy(self):
        from dlgsyy2 import DlgSyy
        d = DlgSyy()
        r = d.exec_()
        if r == 1:
            self.refresh_syy()
        else:
            pass

    def setting(self):
        # from todo import DlgTodo
        # d=DlgTodo()
        # d.exec_()
        from dlgsetting import DlgSetting
        calculator = DlgSetting()
        r = calculator.exec_()
        # logging.info(r)s
        if r == 1:
            # self.set_database()
            self.ui.lineEdit_yqbh.setText(config_json.setting["yqbh"])
            self.setWindowTitle(u"\u6570\u636e\u4e0a\u62a5_" +
                                config_json.setting["sblx"])

        else:
            pass

    def checkSingle(self):
        n = self.model2.rowCount()
        r={}
        for row_idx in range(n):
            record = self.model2.record(row_idx)
            name=str(record.value(record.indexOf("Sampleid")))
            if config_json.setting["pingxing"]==1:
                name=self.remove_pingxing(name)
            if re.match(self.sample_name_pattern,name.strip())!=None:# name.strip()[0:0+2]=="23":
                if r.get(name)!=None:
                    r[name]+=1
                else:
                    r[name]=1
        logging.info(r)
        all=[]
        for k in r.keys():
            if r[k]==1:
                all.append(k)
        if len(all)==0:
            return ""
        else:
            return ",".join(all)
    def check_both(self):
        name = []
        for f in self.fields:
            if f["visible"]:
                name_one = f["title"].split(" ")[0]
                if name_one in name:
                    QMessageBox.information(self, "", "不能同时选择一个元素的两个通道")
                    return True
                else:
                    name.append(name_one)
        return False
    def remove_pingxing(self,a):
        for i in range(len(a)):
            if a[i]=="_":
                return a[:i]        
        return a
    def lims(self):
        if self.check_both():
            return
        n = self.model2.rowCount()
        if n == 0:
            return
        ffbh = self.ui.cmb_ffbh.currentText()
        syy = self.ui.cmb_syy.currentText()
        ysry = self.ui.cmb_ysry.currentText()
        syyqm = self.ui.cmb_syyqm.currentText()
        yqbh = self.ui.lineEdit_yqbh.text()
        queren = ""
        if config_json.setting["checkSingle"]==1:
            single=self.checkSingle()
            if single!="":
                queren = queren+"样品(%s)没有平行样!!!\n" % single 
                queren = queren+"\n"
        queren = queren+"方法编号(%s)\n" % ffbh
        queren = queren+"实验员(%s)\n" % syy
        queren = queren+"一审(%s)\n" % ysry
        queren = queren+"实验员签名(%s)\n" % syyqm
        queren = queren+"仪器编号(%s)\n" % yqbh
        logging.info(["ejff",config_json.setting["ejff"]])
        ejff= self.ui.cmb_ff2.currentText()
        ejfxjs= self.ui.cmb_js2.currentText()
        if config_json.setting["ejff"]==1 and ejff!="" and ejfxjs!="":
            queren = queren+"二级方法(%s)\n" % ejff
            queren = queren+"二级分析技术(%s)" % ejfxjs
        r = QtWidgets.QMessageBox.question(
            self, '输出', queren, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes)
        if r == QtWidgets.QMessageBox.No:
            return
        yqbh=config_json.setting["yqbh"]
        if len(yqbh)>4:
            yqbh=yqbh[-4:]
        if self.ui.lineEdit_filename.text() == "":
            file_name = yqbh + "_" + timestr()
        else:
            file_name = yqbh+"_"+self.ui.lineEdit_filename.text()
        path = config_json.setting["output_folder"]
        filepath = os.path.join(path, file_name)
        self.output_xlsx(filepath)

    def save_as(self):
        FileDialog = QFileDialog(self)
        FileDirectory = FileDialog.getSaveFileName(self)  # 选择目录，返回选中的路径
        fn = FileDirectory[0]
        if fn != "":
            self.save_try(fn)

    def save_try(self, filepath):
        try:
            self.output_xlsx(filepath)
        except:
            traceback.print_exc()
    def getConc0(self,id0):#record.value(record.indexOf("oldid")),record.indexOf(f["name"]))
        logging.info(id0)
        n = self.model.rowCount()
        data={}
        for row in range(n):
            record = self.model.record(row)
            id1 = record.value(record.indexOf("id"))
            logging.info(id1)
            if id1==id0:
                logging.info(self.fields)
                for f in self.fields:
                    if f["visible"] and f.get("ele") != None:
                        data[f["name"]]=record.value(record.indexOf(f["name"]))
                break
        logging.info(data)
        return data
    def output_xlsx(self, filepath):
        n = self.model2.rowCount()
        if n == 0:
            return
        filepath = filepath + ".xlsx"
        # 1. 创建文件对象（指定文件名，模式，编码方式）a模式 为 下次写入在这次的下一行
        wb = openpyxl.Workbook()
        ws = wb.active
        # 3. 构建列表头
        row = ["id", ]
        for f in self.fields:
            if f["visible"] and f.get("ele") != None:
                row.append(f["title"].split(" ")[0])
        row.append("备注")
        ws.append(row)
        for row in range(n):
            record = self.model2.record(row)
            sampleid = str(record.value(record.indexOf("Sampleid")))
            if config_json.setting["pingxing"]==1:
                sampleid=self.remove_pingxing(sampleid)
            row = list([sampleid])
            olddata=self.getConc0(record.value(record.indexOf("oldid")))
            for f in self.fields:
                if f["visible"] and f.get("ele") != None:
                    conc0=olddata.get(f["name"],"") #self.getConc0(record.value(record.indexOf("oldid")),record.indexOf(f["name"]))
                    conc = myfloat(record.value(record.indexOf(f["name"])))
                    if conc0==conc:
                        row.append(conc)
                    else:
                        row.append(str(conc0)+";"+str(conc))
            row.append(record.value(record.indexOf("beizhu")))
            ws.append(row)
        ffbh = self.ui.cmb_ffbh.currentText()
        syy = self.ui.cmb_syy.currentText()
        ysry = self.ui.cmb_ysry.currentText()
        yqbh = self.ui.lineEdit_yqbh.text()
        # tpbh = self.ui.lineEdit_tpbh.text()
        # nb = self.ui.lineEdit_nb.text()
        # bc= self.ui.lineEdit_bc.text()
        # nd= self.ui.lineEdit_nd.text()
        # config_json.setting["nb"]=nb
        # config_json.setting["nd"]=nd
        # config_json.setting["bc"]=bc
        # config_json.setting["tpbh"]=tpbh
        syyqm = self.ui.cmb_syyqm.currentText()
        row = ["ffbh&" + ffbh, "", "", "", ""]
        ws.append(row)
        row = ["syy&" + syy, "", "", "", ""]
        ws.append(row)
        row = ["ysry&" + ysry, "", "", "", ""]
        ws.append(row)
        row = ["yqbh&" + yqbh, "", "", "", ""]
        ws.append(row)
        row = ["syyqm&" + syyqm, "", "", "", ""]
        ws.append(row)
        # row = ["tpbh&" + tpbh, "", "", "", ""]
        # ws.append(row)
        # row = ["nbys&" + nb, "", "", "", ""]
        # ws.append(row)
        # row = ["bc&" + bc, "", "", "", ""]
        # ws.append(row)
        # row = ["nd&" + nd, "", "", "", ""]
        # ws.append(row)
        ff2= self.ui.cmb_ff2.currentText().strip()
        js2= self.ui.cmb_js2.currentText().strip()
        if config_json.setting["ejff"]==1 and ff2 != "" and js2 != "":
            ws.append(["ejff&" + ff2,"", "", "", ""])  # todo
            ws.append(
                ["ejfxjs&" + js2, "", "", "", ""])
        ws.column_dimensions['A'].width = 20.0
        i=0
        for col in ws.columns:
            if i>0:
                ws.column_dimensions[col[0].column_letter].width = 15.0
            i+=1        # other stuff
        # self.output_ws2(wb) #beifen
        # openpyxl.utils.cell.get_column_letter
        ws = wb.create_sheet("sheet2")
        hang=self.output_origin(ws)+1
        # if config_json.setting["sblx"] =="ajl_pdf":
        #     ajlpdf.output_curve(ws,hang)
        # elif config_json.setting["sblx"] =="icap":
        #     icap.output_curve(ws,hang)
        # if config_json.setting["sblx"] =="spec":
        spec1=spec.Spec()
        spec1.spec_output_curve(self.fields,ws,hang)
        # .spec_output_curve(ws,hang)
        wb.save(filepath)
        self.ui.textEdit.insertPlainText(filepath + "\n")
        scrollbar = self.ui.textEdit.verticalScrollBar()
        scrollbar.setSliderPosition(scrollbar.maximum())
    def spec_output_curve(self,ws,hang):
        ts=[]
        eles=[]
        for f in self.fields:
            if f["visible"] and f.get("ele") != None:
                eles.append(f.get("ele"))
        ts=self.getImages(eles)
        self.outputImages(ws,hang,ts)
    def getImages(self,eles):
        r=[]
        for ele in eles:
            curve=self.getImage_ele(ele)
            if curve!=None:
                r.append(curve)
        return r
    def getImage_ele(self,ele):
        xishu=myglobal.db.getXishuCurrent(myglobal.methodid,ele)
        data=myglobal.db.getCurveData(myglobal.methodid,ele)
        if xishu!=None:
            [x2,x1,x0,r,curveid,must00,ci]=xishu
            params=[]
            params.append("ele="+ele)
            params.append("x2="+str(x2))
            params.append("x1="+str(x1))
            params.append("x0="+str(x0))
            params.append("r="+str(r))
            filename=os.path.join(getpath.getpath(),"images",str(myglobal.methodid)+"_"+ele+"_"+str(curveid)+".jpg")
            return (filename,params,data,ele)
        else:
            return None
    def outputImages(self,ws,hang,ts):#outputsheet,pdf filename,0-n page
        ss=QtWidgets.qApp.screens()
        if len(ss)<1:
            rowh=13.5/72.0*96
        else:
            rowh=13.5/72.0*ss[0].physicalDotsPerInch() #bang to pixel
        at_row=hang
        for i in range(len(ts)):
            (filename,paras,data,ele)=ts[i]
            ws["A"+str(at_row)]="sampleid"
            ws["B"+str(at_row)]=ele+"-STD"
            ws["C"+str(at_row)]=ele
            ws["D"+str(at_row)]=ele+"'"
            j=1
            for one in data:
                ws["A"+str(at_row+j)]=one[0]
                ws["B"+str(at_row+j)]=one[1]
                ws["C"+str(at_row+j)]=one[2]
                ws["D"+str(at_row+j)]=one[3]
                j+=1
            if os.path.exists(filename):
                img = Image(filename)
                img.width=300#not too big
                img.height=200
                n=int((img.height)/rowh)+2
                ws.add_image(img, "F"+str(at_row))  # 图片 插入 A1 的位置上
            else:
                n=0
            # at_row=i*n+hang
            for j in range(len(paras)):
                ws["E"+str(at_row+j)]=paras[j]
            ws.column_dimensions['E'].width = 15.0
            if len(data)>n:
                at_row=at_row+len(data)
            else:
                at_row=at_row+n
    def output_origin(self, ws):
        n = self.model.rowCount()
        row = ["id"]
        for f in self.fields:
            if f.get("ele")!=None:
                if f.get("xishu")!=None:
                    row.append(f["ele"]+" "+f["wave"]+ "\n("+f["title"].split(" ")[0]+" "+str(f["xishu"])+")")
                else:
                    row.append(f["title"])
        ws.append(row)
        hang=1
        for row in range(n):
            record = self.model.record(row)
            row = list([record.value(record.indexOf("Sampleid"))])
            for f in self.fields:
                if f.get("ele")!=None:
                    conc = record.value(record.indexOf(f["name"]))
                    row.append(conc)
            ws.append(row)
            hang+=1
        return hang
    def gen_idstr(self):
        r = "("
        for i in range(len(self.ids)):
            r += str(self.ids[i]) + ","
        if len(self.ids) < 1:
            pass
        else:
            r = r[: -1]
        r += ")"
        # logging.info(r)
        self.idStr = r
        return r

    def clear(self):
        # self.ids = []
        # self.gen_idstr()
        cmd="delete from Result where calced=1"
        myglobal.db.sql_cmd(cmd)
        self.model2.select()#setFilter(" id in  " + self.idStr)

    def unselect(self):
        selections = self.ui.tableView_report.selectionModel()
        list1 = selections.selectedIndexes()
        for i in range(len(list1)):
            current = list1[i]
            if current.column() == 0:
                row = current.row()
                record = self.model2.record(row)
                idCol = record.indexOf("id")  #
                id1 = record.value(idCol)
                cmd="delete from Result where id=%d" % id1
                myglobal.db.sql_cmd(cmd)
                # self.ids.remove(id1)
        self.model2.select()
        # self.gen_idstr()
        # self.model2.setFilter(" id in  " + self.idStr)

    def select(self):
        # logging.info("select")
        selections = self.ui.tableView.selectionModel()
        list1 = selections.selectedIndexes()
        for i in range(len(list1)):
            current = list1[i]
            # logging.info(current,dir(current))
            if current.column() == 0:
                row = current.row()
                record = self.model.record(row)
                self.calc_one(record)
        self.model2.select()
        #         idCol = record.indexOf("id")  #
        #         id1 = record.value(idCol)
        #         if id1 in self.ids:
        #             pass
        #         else:
        #             self.ids.append(id1)
        # self.gen_idstr()
        # self.model2.setFilter(" id in  " + self.idStr)


if __name__ == "__main__":
    import sys
    a = SingleApplication(sys.argv)
    a.lastWindowClosed.connect(a.quit)
    w = MainW()
    w.show()
    sys.exit(a.exec_())
